var DXML;
if (!DXML) {
    DXML = {
    };
}
DXML.boutXML = null;
DXML.firstPeriod = null;
DXML.secondPeriod = null;
DXML.homeTeam = null;
DXML.awayTeam = null;
//DXML.defaultBout = "test";
//DXML.defaultLeague = "index";
DXML.homeTeamIcon = "assets/images/home.png";
DXML.awayTeamIcon = "assets/images/away.png";

function extractRoster(team, showNonSkaters) {
    var retval = [];
    $(team).find('person').each(function(index, value) {
        var role = $(value).attr('role');
        if (!role) {
            role = "skater";
        }
        if (showNonSkaters || role == "skater") {
            retval.push({name:$(value).attr('name'),number:$(value).attr('number'), role:role});
        }
    });
    return retval;
}
function extractName(team, altTeam) {
    // get the best name, given that altTeam and this team may both be "All Stars" (for example)
    var teamLeague = $(team).attr('league');
    var teamName = $(team).attr('name');
    var altLeague = $(altTeam).attr('league');
    var altName = $(altTeam).attr('name');
    var teamName1 = teamName.replace(/\W+/g, "");
    if (teamName1.length == 0) {
        return teamLeague
    }
    var altName1 = altName.replace(/\W+/g, "");
    if (altName1.toUpperCase() == teamName1.toUpperCase()) {
        return teamLeague;
    }
    return teamName;
}
function oddEvenTables() {
    $("table.oddeven tr:even").addClass('even');
    $("table.oddeven tr:odd").addClass('odd');
}
function addPlayerHighlighting(selector) {
    $(selector).find('.player').hover(
        function()
        {
            var uid = $(this).attr('uid');
            if (uid && uid != '???') {
                $(selector).find('.player[uid='+ uid +']').parent().addClass("highlight");
            }
        },
        function()
        {
            $('.player').parent().removeClass("highlight");
    });
    $(selector).find('.player').click( function() {
        $('.player').parent().removeClass("highlightcell");
        var uid = $(this).attr('uid');
        if (uid && uid != '???') {
            $(selector).find('.player[uid='+ uid +']').parent().addClass("highlightcell");
        }
    });
}

function formatMSS(seconds) {
    var minutes = Math.floor(seconds / 60);
    seconds = Math.floor(seconds - minutes * 60);
    if (seconds < 10)
        return minutes + ":0" + seconds
    return minutes + ":" + seconds
}
    function threeDigits(x, force) {
        if (x === null || x === undefined) {
            return "-";
        }
        if (x != x) {
            return "N/A";
        }
        if (x < 0) {
            return "-" + threeDigits(-x, force);
        }
        if (x == Math.floor(x)) {
            if (force)
                return (""+x+".0000").substring(0, 4);
            return "" + x;
        }
        if (x * 1000 < 1) {
            return "0.00";
        }
        if (x >= 100) {
            return "" + Math.round(x);
        }
        if (x >= 10) { // one decimal
            x = Math.round(x * 10);
            x = "" + x;
            return x.substring(0, 2) + "." + x.substring(2, 3);
        }
        // we've got (0..10)
        retval = "" + Math.floor(x);
        x = x - Math.floor(x);
        retval += ".";
        x = x * 10;
        retval += "" + Math.floor(x);
        x = x - Math.floor(x);
        x = x * 10;
        retval += "" + Math.floor(x);
        return retval;
    }
    function ColorTD(x, force) {
        if (x != x)
            return "N/A";
        if (x < 0)
            return "<span class='down'>" + threeDigits(x, force) + "</span>";
        else if (x == 0)
            return "<span class='zero'>" + threeDigits(x, force) + "</span>";
        else
            return "<span class='up'>" + threeDigits(x, force) + "</span>";
    }
    function percent(x,y) {
        if (y == 0)
            return "-";
        return Math.floor(100 * x / y + 0.5) + "%";
    }

DXML.penaltyCodes = {
    '4': "Fourth Minor",
    4: "Fourth Minor",
    'B': "Back Block",
    'H': "Block w/ Head",
    'X': "Track Cut",
    'C': "Direction of Play",
    'E': "Elbows",
    'F': "Forearms",
    'A': "High Block",
    'I': "Illegal Procedure",
    'L': "Low Block",
    'M': "Multi-Player Block",
    'O': "Out of Bounds Block",
    'P': "Out of Play Block",
    'S': "Skate Out of Bounds",
    'N': "Insubordination",
    'G': "(Gross) Misconduct",
    'Z': "Delay of Game",
    'PM': "Penalty Minutes",
    'FO': "Foul Out"
};

DXML.jamPassScoreTally = "<div class=\"point\"></div>";

function formatJamPassScore(passes, num, hasSP) {
    num = num - 1;
    if (num >= passes.length)
        return "";
    var pass = passes[num];
    if (pass) {
        var retval = "";
        if (hasSP) {
            retval += DXML.jamStarPassMarker;
        }
        var pts = Number($(pass).attr("points"));
        if (pts == 0)
            return retval + "0";
        while (pts) {
            retval += DXML.jamPassScoreTally;
            pts--;
        }
        return retval;
    }
    return "";
}

DXML.jamLeadMarker = "<img src=\"assets/images/lead.png\" title=\"Has Lead Jammer Status\"/>";
DXML.jamLostMarker = "<img src=\"assets/images/lost.png\" title=\"Lost Lead Jammer Status\"/>";
DXML.jamCalledMarker = "<img src=\"assets/images/call.png\" title=\"Jam Called\"/>";
DXML.jamNPMarker = "<img src=\"assets/images/nopass.png\" title=\"Initial Pass Not Completed\"/>";
DXML.jamInjMarker = "<img src=\"assets/images/injury.png\" title=\"Jam Ended with Injury\"/>";
DXML.jamStarPassMarker = "<img src=\"assets/images/starpass.png\" title=\"Star Pass\"/>";


DXML.inBoxIcon = "<img src=\"assets/images/chair.png\"/>";
DXML.enterBoxIcon = "<img src=\"assets/images/enterbox.png\"/>";
DXML.exitBoxIcon = "<img src=\"assets/images/exitbox.png\"/>";
DXML.jammerIcon = "<img src=\"assets/images/jammer.png\"/>";
DXML.pivotIcon = "<img src=\"assets/images/pivot.png\"/>";
DXML.blockerIcon = "<img src=\"assets/images/blocker.png\"/>";

DXML.jamStartInBoxMarker = "<span title=\"Started jam in box, did not exit\">" + DXML.inBoxIcon + "</span>";
DXML.jamStartInBoxExitMarker = "<span title=\"Started jam in box\">" + DXML.inBoxIcon + DXML.exitBoxIcon + "</span>";
DXML.jamEnterBoxMarker = "<span title=\"Entered box, did not exit\">" + DXML.enterBoxIcon + DXML.inBoxIcon + "</span>";
DXML.jamEnterExitBoxMarker = "<span title=\"Box Trip\">" + DXML.enterBoxIcon + DXML.inBoxIcon + DXML.exitBoxIcon +  "</span>";

DXML.jamNoPivotMarker = "<span class=\"skaterPositionIcon\" title=\"Not Fielded As Pivot\">" + DXML.blockerIcon + "</span>";
DXML.jamJammerMarker = "<span class=\"skaterPositionIcon\" title=\"Jammer\">" + DXML.jammerIcon + "</span>";
DXML.jamPivotMarker = "<span class=\"skaterPositionIcon\" title=\"Pivot\">" + DXML.pivotIcon + "</span>";
DXML.jamBlockerMarker = "<span class=\"skaterPositionIcon\" title=\"Blocker\">" + DXML.blockerIcon + "</span>";

DXML.homeIcons = {};
DXML.awayIcons = {};

DXML.leagueIcons = {};
DXML.leagueColors = {};
DXML.homeColor = "darkgray";
DXML.awayColor = "lightgray";

function leagueColorsForTeam(team) {
    var leagueName = $(team).attr("league");
    var teams = DXML.leagueColors[leagueName];
    if (teams) {
        return teams[$(team).attr("name")];
    }
    return null;
}
function leagueIconsForTeam(team) {
    var leagueName = $(team).attr("league");
    var teams = DXML.leagueIcons[leagueName];
    if (teams) {
        return teams[$(team).attr("name")];
    }
    return null;
}
function iconInformationFromTeam(team) {
    var icons = {};
    var genericIcon = $(team).attr("icon");
    $(team).find("icon").each(function(index, icon) {
        var size = $(icon).attr("size");
        var src = $(icon).attr("src");
        if (!genericIcon) {
            genericIcon = src; // grab first icon we have
        }
        icons[size] = src;
    });
    // build other icons from generic (or first sized one we find)
    if (genericIcon) {
        if (!icons.large) icons.large = genericIcon;
        if (!icons.medium) icons.medium = genericIcon;
        if (!icons.small) icons.small = genericIcon;
        if (!icons.tiny) icons.tiny = genericIcon;
    } else {
        return null;
    }
    return icons;
}
function colorInformationFromTeam(team) {
    var colors = {};
    var genericColor = $(team).attr("color");
    colors.color = genericColor;
    return colors;
}
function buildIconsForTeam(team, side, dflt) {
    // use the league specified info but override with icons specified in the team in the bout
    var teamSpecific = iconInformationFromTeam(team);
    var icons;
    if (dflt && teamSpecific) {
        icons = $.merge({}, dflt, teamSpecific);
    } else if (dflt) {
        icons = dflt;
    } else if (teamSpecific) {
        icons = teamSpecific;
    } else if (side == "home") {
        icons = {
            large: DXML.homeTeamIcon,
            medium: DXML.homeTeamIcon,
            small: DXML.homeTeamIcon,
            tiny: DXML.homeTeamIcon
        };
    } else if (side == "away") {
        icons = {
            large: DXML.awayTeamIcon,
            medium: DXML.awayTeamIcon,
            small: DXML.awayTeamIcon,
            tiny: DXML.awayTeamIcon
        };
    } else {
        return;
    }
    DXML[side + "Icons"] = icons;
    // now construct the style - first remove the old one
    $('style[id="' + side + 'Styles"]').attr('disabled', 'disabled');
    $('style[id="' + side + 'Styles"]').remove();
    
    $("<style>")
        .prop("type", "text/css")
        .prop("id", side + "Styles")
        .html("." + side + "LargeIcon { display:block; width:100px; height:100px; background-size:100px; background-image: url(" + icons.large +"); }" +
        "." + side + "MediumIcon { display:block; width:64px; height:64px; background-size:64px; background-image: url(" + icons.medium +"); }" +
        "." + side + "SmallIcon { display:block; width:32px; height:32px; background-size:32px; background-image: url(" + icons.small +"); }" +
        "." + side + "TinyIcon { display:block; width:20px; height:20px; background-size:20px; background-image: url(" + icons.tiny +"); }"
        )
        .appendTo("head");
}
function loadDerbyXML(document) {
    var dxml = document.firstChild;
    DXML.boutXML = $(dxml).find('bout')[0];
    var teams = $(DXML.boutXML).find('team');
    DXML.homeTeam = teams[0];
    DXML.awayTeam = teams[1];
    buildIconsForTeam(DXML.homeTeam, "home", leagueIconsForTeam(DXML.homeTeam));
    buildIconsForTeam(DXML.awayTeam, "away", leagueIconsForTeam(DXML.awayTeam));
    var periods = $(DXML.boutXML).find('period');
    DXML.firstPeriod = periods[0];
    DXML.secondPeriod = periods[1];
    if ($('#overview').length) {
        prepareOverviewPage();
    }
    if ($('#skatersPage').length) {
        prepareSkatersPage();
    }
    if ($('#jamsPage').length) {
        prepareJamsPage();
    }
}

